<template>

    <FormDrawer ref="formDrawerRef" title="產品規格" @submit="submit" destroy-on-close size="60%">
        <el-form :model="form" ref="formRef"  label-width="80px" :inline="false">

            <el-form-item label="规格类型" prop="is_spec">
                <el-radio-group v-model="form.is_spec">
                    <el-radio :label="0" border>單規格</el-radio>
                    <el-radio :label="1" border>多規格</el-radio>
                </el-radio-group>
            </el-form-item>

            <template v-if="form.is_spec == 0">
                <el-form-item label="價格" prop="price">
                    <el-input v-model="form.price" type="number" style="width:40%;" />
                </el-form-item>
                <el-form-item label="成本" prop="cost">
                    <el-input v-model="form.cost" type="number" style="width:40%;" />
                </el-form-item>
                <el-form-item label="庫存" prop="num">
                    <el-input v-model="form.num" type="number" style="width:40%;" />
                </el-form-item>
            </template>

            <template v-else>
                 <Sku></Sku>
                 <SkuTable></SkuTable>   
            </template>
        </el-form>                                                                                                                                                                              
    </FormDrawer>
</template>

<script setup>
import { ref, reactive } from "vue"
import { show, update } from "@/api/product.js"
import FormDrawer from "@/components/FormDrawer.vue";
import { msg } from "@/composables/util"
import SkuTable from "./SkuTable.vue"
import Sku from "./Sku.vue"

import { initSku,
    productId,sku_table } from "@/composables/useSku.js"

const dialogVisible = ref(false)
const formDrawerRef = ref(null)
const form = ref({
    is_spec: 0,
    price: 0,
    cost: 0,
    num: 0
})

const open = (row) => {

    productId.value = row.id
    show(productId.value).then(res => {
        form.value.is_spec = res.is_spec
        form.value.price = res.price
        form.value.cost = res.cost
        form.value.num = res.num

        initSku(res)
        formDrawerRef.value.open()
    })
    dialogVisible.value = true
}
const emit = defineEmits(["reloadData"])
const submit = () => {
    let data=form.value
    if(form.value.is_spec==1){
        data.productsku=sku_table.value
        
    }
 
    update(productId.value, data).then(res => {
        msg("設置規格成功")
        formDrawerRef.value.close()
        emit("reloadData")
    })
}

defineExpose({
    open
})
</script>